package com.example.udpNetThread;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @Author 郅占伟
 * @ClassName ReceiveData
 * @Description TODO
 * @Date 2024年05月15日
 * @Version: 1.0
 */
public class ReceiveData extends Thread {
    @Override
    public void run() {
        try {
            // 创建接收端 Socket 对象
            InetAddress inetAddress = InetAddress.getByName("127.0.0.1");
            DatagramSocket datagramSocket = new DatagramSocket(10086, inetAddress);

            while (true) {
                // 创建数据包
                byte[] bytes = new byte[1024];
                DatagramPacket datagramPacket = new DatagramPacket(bytes, bytes.length);

                // 接收数据
                datagramSocket.receive(datagramPacket);

                // 解析数据
                System.out.println(datagramPacket);
                String hostAddress = datagramPacket.getAddress().getHostAddress();
                String s = new String(datagramPacket.getData(), 0, datagramPacket.getLength());

                System.out.println("接收端：从" + hostAddress + "主机接收到的数据是： " + s);

                if ("bye".equals(s)) {
                    System.out.println("**********聊天室关闭************");
                    datagramSocket.close();
                    break;
                }
            }

        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
